﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Application.Request;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;

namespace Admin.NET.Application.Service;

/// <summary>
/// 招聘实体接口
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Name = "Zhaopin", Order = 200)]
public class ZhaopinService : IDynamicApiController {

    private readonly UserManager _userManager;

    /// <summary>
    /// 数据库仓储接口
    /// </summary>
    private readonly ISqlSugarRepository<ZhaopinEntity> _repository;

    private IHttpContextAccessor _httpContext;

    public ZhaopinService(UserManager userManager, IHttpContextAccessor httpContext, SqlSugarRepository<ZhaopinEntity> repository) {
        _userManager = userManager;
        _repository = repository;
        _httpContext = httpContext;
    }


    #region 1.0 分页查询数据 +Task<SqlSugarPagedList<ZhaopinEntity>> GetList([FromQuery] ListZhaopinInput input)
    [HttpGet]
    [AllowAnonymous]
    public async Task<SqlSugarPagedList<ZhaopinEntity>> GetList([FromQuery] ListZhaopinInput input) {
         
        var remoteIPv4 = _httpContext.HttpContext.GetRemoteIpAddressToIPv4 ( ) ;
        // 判断是否为本地IP
        (string ipLocation, double? longitude, double? latitude) = CommonUtil.GetIpAddress(remoteIPv4);
        List<String> ranges =  App.GetConfig<List<String>>("IpLocaiton", true);

        Console.WriteLine("remoteIPv4={0},addr={1}", remoteIPv4, ipLocation);
        if (!ranges.Contains( ipLocation  )) {
            return new SqlSugarPagedList<ZhaopinEntity>(); 
        }

        List<int?> listStatus = new List<int?>();
        if (!String.IsNullOrWhiteSpace(input.Status)) {

            input.Status.Split(',').ForEach(t => {
                if (int.TryParse(t, out int val)) {
                    listStatus.Add(val);
                }
            });
        }

        SqlSugarPagedList<ZhaopinEntity> list = await _repository.AsQueryable()
            .WhereIF(!String.IsNullOrWhiteSpace(input.Keyword), it => it.Company.Contains(input.Keyword)
                || it.Title.Contains(input.Keyword)
                || it.TagsJson.Contains(input.Keyword)
                || it.PhoneNumbers.Contains(input.Keyword) 
                || it.Location.Contains(input.Keyword)
             )
             .WhereIF(listStatus.Count > 0, it => listStatus.Contains(it.Status))
             .WhereIF(!string.IsNullOrWhiteSpace(input.Title), it => it.Title.Contains(input.Title))
             .OrderByDescending(it => it.PostedDate)
             .ToPagedListAsync(input.Page, input.PageSize);

        // 查询所有招聘数据
        return list;
    }
    #endregion

    #region 2.0 主键获取实体 +Task<ZhaopinEntity> GetById(string id) 
    [HttpGet("{id}")]
    [AllowAnonymous]
    public async Task<ZhaopinEntity> GetById(string id) {
        ZhaopinEntity entity = await _repository.GetByIdAsync(long.Parse(id));
        if (entity == null) {
            throw new Exception("招聘不存在");
        }

        int viewCount = entity.ViewCount ?? 0;
        _repository.AsUpdateable()
            .SetColumns(it => it.ViewCount == viewCount + 1)
            .Where(it => it.Id == entity.Id)
            .ExecuteCommand();
        return entity;
    }
    #endregion

    #region 3.0 新增实体数据 +Task Create([FromBody] ZhaopinRequest input) 
    [HttpPost]
    public async Task Create([FromBody] ZhaopinRequest input) {
        if (input == null) {
            throw Oops.Oh("请求数据不能为空");
        }
        ZhaopinEntity entity = input.Adapt<ZhaopinEntity>();
        entity.CreateUserId = _userManager.UserId;
        entity.CreateUserName = _userManager.Account;
        entity.PostedDate = DateTime.Now;
        entity.Status = 100;

        await _repository.Context.Insertable(entity)
            .CallEntityMethod(it => it.Creater()).ExecuteCommandAsync();
    }
    #endregion

    #region 3.1 发布实体数据 +Task ZhaopinPublish([FromBody] ZhaopinRequest input) 
    [AllowAnonymous]
    [HttpPost("publish")]
    public async Task ZhaopinPublish([FromBody] ZhaopinRequest input) {
        if (input == null) {
            throw Oops.Oh("请求数据不能为空");
        }
        ZhaopinEntity entity = input.Adapt<ZhaopinEntity>();
        entity.CreateUserName = "publish";
        entity.PostedDate = DateTime.Now;
        entity.Status = 100;

        await _repository.Context.Insertable(entity)
            .CallEntityMethod(it => it.Creater()).ExecuteCommandAsync();
    }
    #endregion

    #region 4.0 移除主键的数据 +Task Delete(string id) 
    [HttpDelete("{id}")]
    public async Task Delete(string id) {
        if (string.IsNullOrWhiteSpace(id)) {
            throw Oops.Oh("ID不能为空");
        }
        // 查询所有招聘数据
        await _repository.DeleteByIdAsync(long.Parse(id));
    }
    #endregion

    #region 5.0 修改实体数据 +Task Update([FromBody] ZhaopinRequest input)
    [HttpPut]
    public async Task Update([FromBody] ZhaopinRequest input) {
        if (input == null) {
            throw Oops.Oh("请求数据不能为空");
        }
        if (string.IsNullOrWhiteSpace(input.Id)) {
            throw Oops.Oh("ID不能为空");
        }
        ZhaopinEntity entity = input.Adapt<ZhaopinEntity>();
        entity.UpdateTime = DateTime.Now;
        entity.UpdateUserId = _userManager.UserId;
        // 更新招聘数据 
        if (!await _repository.UpdateAsync(entity)) {
            throw Oops.Oh("更新招聘数据失败");
        }

    }
    #endregion


}